<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>类型模板管理</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="../css/style.css">
	<script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../plugins/select2/select2.css" />
    <link rel="stylesheet" href="../plugins/select2/select2-bootstrap.css" />
    <script src="../plugins/select2/select2.min.js" type="text/javascript"></script>
	<!-- bootstrap-table -->
	<link rel="stylesheet" type="text/css" href="../plugins/bootstrap-table/dist/bootstrap-table.css"/>
	<script type="text/javascript" src="../plugins/bootstrap-table/dist/bootstrap-table.js"></script>
	<script type="text/javascript" src="../plugins/bootstrap-table/dist/locale/bootstrap-table-zh-CN.js"></script>

</head>

<body class="hold-transition skin-red sidebar-mini" >
  <!-- .box-body -->

                    <div class="box-header with-border">
                        <h3 class="box-title">商品类型模板管理</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-default" title="新建" data-toggle="modal" data-target="#editModal" ><i class="fa fa-file-o"></i> 新建</button>
                                        <button type="button" class="btn btn-default" onclick="deleteByIds()" title="删除"><i class="fa fa-trash-o"></i> 删除</button>

                                        <button type="button" class="btn btn-default" title="刷新" onclick="window.location.reload();"><i class="fa fa-refresh"></i> 刷新</button>
                                    </div>
                                </div>
                            </div>
                            <div class="box-tools pull-right">
                                <div class="has-feedback">
							                  分类模板名称：<input type="text" id="typeName">
									<button class="btn btn-default" onclick="table_refrese()">查询</button>
                                </div>
                            </div>
                            <!--工具栏/-->
							<div id="table"></div>
                        <!-- 数据表格 /-->


						</div>

                     </div>
                    <!-- /.box-body -->




<!-- 编辑窗口 -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">商品类型模板增加</h3>
		</div>
		<div class="modal-body">

			<table class="table table-bordered table-striped" width="800px">
		      	<tr>
		      		<td>商品类型</td>
		      		<td><input  class="form-control"  placeholder="商品类型">  </td>
		      	</tr>
		      	<tr>
		      		<td>关联品牌</td>
		      		<td>
						<select id="brands" style="width: 100%" multiple>
							<option th:each="bran:${brand}" th:value="${bran.id}">[[${bran.name}]]</option>
						</select>
		      		</td>
		      	</tr>
		      	<tr>
		      		<td>关联规格</td>
		      		<td>
						<select id="specs" style="width: 100%" multiple>
							<option th:each="spe:${spec}" th:value="${spe.id}">[[${spe.specName}]]</option>
						</select>
		      		</td>
		      	</tr>
		      	<tr>
		      		<td>扩展属性</td>
		      		<td>
		      			<div class="btn-group">
                             <button type="button" class="btn btn-default" title="新增扩展属性"><i class="fa fa-file-o"></i> 新增扩展属性</button>
                        </div>
						<table class="table table-bordered table-striped"  width="800px">
							<thead>
								<tr>
								    <td><input type="checkbox" class="icheckbox_square-blue"></td>
									<td>属性名称</td>
									<td>操作</td>
								</tr>
							</thead>
							<tbody id="types">
								<tr>
									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
									<td><input class="form-control" name="td1" placeholder="属性名称" ></td>
									<td><button type="button" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>
								</tr>
								<tr>
									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
									<td><input class="form-control" name="td2" placeholder="属性名称" ></td>
									<td><button type="button" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>
								</tr>
							</tbody>
						</table>
		      		</td>
		      	</tr>
			 </table>

		</div>
		<div class="modal-footer">
			<button class="btn btn-success" data-dismiss="modal" aria-hidden="true" onclick="toSave()">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>

<!--         回显         -->
<div class="modal fade" id="updateEditModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabels">商品类型模板增加</h3>
		</div>
		<div class="modal-body">
			<input type="hidden" name="id" id="typeId">
			<table class="table table-bordered table-striped" width="800px">
		      	<tr>
		      		<td>商品类型</td>
		      		<td><input  class="form-control" id="name" name="name" placeholder="商品类型">  </td>
		      	</tr>
		      	<tr>
		      		<td>关联品牌</td>
		      		<td>
						<select id="brand2" style="width: 100%" multiple>
							<option th:each="bran:${brand}" th:value="${bran.id}">[[${bran.name}]]</option>
						</select>
		      		</td>
		      	</tr>
		      	<tr>
		      		<td>关联规格</td>
		      		<td>
						<select id="spec2" style="width: 100%" multiple>
							<option th:each="spe:${spec}" th:value="${spe.id}">[[${spe.specName}]]</option>
						</select>
		      		</td>
		      	</tr>
		      	<tr>
		      		<td>扩展属性</td>
		      		<td>
		      			<div class="btn-group">
                             <button type="button" class="btn btn-default" title="新增扩展属性"><i class="fa fa-file-o"></i> 新增扩展属性</button>
                        </div>
						<table class="table table-bordered table-striped"  width="800px">
							<thead>
								<tr>
								    <td><input type="checkbox" class="icheckbox_square-blue"></td>
									<td>属性名称</td>
									<td>操作</td>
								</tr>
							</thead>
							<tbody id="type2">
								<tr>
									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
									<td><input class="form-control" id="td1" name="td1" placeholder="属性名称" ></td>
									<td><button type="button" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>
								</tr>
								<tr>
									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
									<td><input class="form-control" id="td2" name="td2" placeholder="属性名称" ></td>
									<td><button type="button" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>
								</tr>
							</tbody>
						</table>
		      		</td>
		      	</tr>
			 </table>

		</div>
		<div class="modal-footer">
			<button class="btn btn-success" data-dismiss="modal" aria-hidden="true" onclick="toTypeUpdate()">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>
  <script>
	  $(function () {
		  $("#brands").select2();
		  $("#brand2").select2();
		  $("#specs").select2();
		  $("#spec2").select2();
	  })
			$('#table').bootstrapTable({
			//请求地址
			url: '/type/getTypeInfo',
			method: 'post',//请求方式
			toolbar: '#toolbar',              //工具按钮用哪个容器
			striped: true,//是否显示行间隔色
			cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
			// pagination: true,//是否显示分页（*）
			contentType: "application/x-www-form-urlencoded",//设置请求方式
			sortOrder: "desc",//排序方式
			// sortName:"newsId",//排序字段/**/
			sidePagination: "server",//分页方式：client客户端分页，server服务端分页（*）
			pageNumber: 1,//初始化加载第一页，默认第一页,并记录
			pageSize: 3,//每页的记录行数（*）
			pageList: [1, 3, 5],//可供选择的每页的行数（*）
			// search: true,//是否显示表格搜索
			// strictSearch: true,//严格搜索
			showColumns: true,//是否显示所有的列（选择显示的列）
			showRefresh: true,//是否显示刷新按钮
			minimumCountColumns: 2,             //最少允许的列数
			clickToSelect: true,                //是否启用点击选中行
			uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
			showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
			// cardView: true,                    //是否显示详细视图
			detailView: true,                  //是否显示父子表
			//得到查询的参数
			queryParams : function (params) {
			//这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
			var temp = {
			// pageSize: params.limit,                         //每页条数
			// pageNum: (params.offset / params.limit) + 1,   //当前页数
				name: $("#typeName").val()
		};
			return temp;
		},

			//列
			columns: [{
			checkbox: true,
			visible: true                  //是否显示复选框
		},{
			//实体类属性
			field: 'id',
			//表头
			title: '模板ID'
		},{
			field: 'name',
			title: '分类模板名称',
		},{
			field: 'specIds',
			title: '关联品牌',
				formatter : function (value,row,index){
					var typeJson = JSON.parse(value);
					var str = "";
					for (var i = 0; i < typeJson.length; i++) {
						str += ","+typeJson[i].text;
					}
					str = str.substr(1);
					return str;
				}
		}, {
			field: 'brandIds',
			title: '关联规格',
				formatter : function (value,row,index){
					var typeJson = JSON.parse(value);
					var str = "";
					for (var i = 0; i < typeJson.length; i++) {
						str += ","+typeJson[i].text;
					}
					str = str.substr(1);
					return str;
				}
		},{
			field: 'customAttributeItems',
			title: '扩展属性',
				formatter : function (value,row,index){
					var typeJson = JSON.parse(value);
					var str = "";
					console.log(typeJson);
					for (var i = 0; i < typeJson.length; i++) {
						if (!typeJson[i].text == ''){
							str += ","+typeJson[i].text;
						}
					}
					str = str.substr(1);
					return str;
				}
		},{
			field: 'id',
			title: '操作栏',
			formatter : function (value,row,index) {
			//操作栏的格式化
			var id = value;
			var result = "";
			result += "<a href='javascript:;' class='btn btn-xs blue' data-toggle='modal' data-target='#updateEditModal' onclick=\"EditViewById('" + id + "')\" title='编辑'><span class='glyphicon glyphicon-pencil'></span></a>";
			result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"deleteByIds('" + id + "')\" title='删除'><span class='glyphicon glyphicon-remove'></span></a>";
			return result;
		}
		}, ]
		});
			////////////////          点击刷新            //////////////////////////
			function table_refrese(){
			// 刷新当前table -> 请求一次
			$("#table").bootstrapTable("refresh");
		}

	//	增加
	  function toSave() {

		  // 获取 先选择的数据集    Brand
		  var brandSelect = $("#brands").select2("data");
		  // 定义数组  存放 遍历选择的数据
		  var brandList = [];
		  for (var i = 0; i < brandSelect.length; i++) {
			  var brands = {id:brandSelect[i].id,text:brandSelect[i].text.trim()}
			  brandList.push(brands);
		  }
		  // 将数据转为 json 字符串
		  var brandJson = JSON.stringify(brandList);

		  //                specs
		  var specSelect = $("#specs").select2("data");
		  var specList = [];
		  for (var i = 0; i <specSelect.length ; i++) {
			  var specs = {id:specSelect[i].id,text:specSelect[i].text.trim()}
			  specList.push(specs);
		  }
		  var specJson = JSON.stringify(specList);

		  //            types
		  // 先把前端的对象转换成 字符串   然后后端再进行处理
		  var typeList = [];
		  var type1 = {text:$("[name=td1]").val()}
		  var type2 = {text:$("[name=td2]").val()}

		  typeList.push(type1);
		  typeList.push(type2);
		  var typeListJson = JSON.stringify(typeList);

		  $.ajax({
			  url : "/type/insertTypeInfo",
			  type : "post",
			  dataType : "json",
			  async : true,
			  data : {name:$("[name=name]").val(),specIds:specJson,brandIds:brandJson,customAttributeItems:typeListJson},
			  success : function (result) {
				  if (result.code == 10000){
					  window.location.reload();
					  alert(result.message);
				  }else if (result.code == 10001){
					  alert(result.message)
				  }
			  },
			  error : function (result) {
				  alert("网络错误,增加失败");
			  }
		  })
	  }
	  // 回显
	  function EditViewById(id) {
		  $.ajax({
			  url : "/type/updateType?id="+id,
			  type : "post",
			  dataType : "json",
			  async : false,
			  success : function (result) {
				  var type = result.rows;
				  //   brand
				  var brands = type.brandIds;
				  var brandJson = JSON.parse(brands);
				  var brandss = [];
				  for (var i = 0; i < brandJson.length; i++) {
					  brandss.push(brandJson[i].id);
				  }
				  // select2 提供的回显方法
				  $("#brand2").val(brandss).trigger("change");

				  //   spec
				  var specs = type.specIds;
				  // 将数据转为 json
				  var specJson = JSON.parse(specs);
				  // 定义数组  存放 遍历选择的数据
				  var specss = [];
				  for (var i = 0; i < specJson.length; i++) {
					  specss.push(specJson[i].id);
				  }
				  $("#spec2").val(specss).trigger("change");

				  //   type
				  $("#typeId").val(type.id);
				  $("#name").val(type.name);

				  var custom = type.customAttributeItems;
				  var customJson = JSON.parse(custom);
				  if (customJson.length==1){
					  $("#td1").val(customJson[0].text);
				  }else if (customJson.length==2){
				  	$("#td1").val(customJson[0].text);
				  	$("#td2").val(customJson[1].text);
				  }
			  },
			  error : function (result) {
				  alert("网络错误");
			  }
		  })
	  }


// 	  //   修改
	  function toTypeUpdate() {
		  // 获取 先选择的数据集    Brand
		  var brandSelect = $("#brand2").select2("data");
		  // 定义数组  存放 遍历选择的数据
		  var brandList = [];
		  for (var i = 0; i < brandSelect.length; i++) {
			  var brands = {id:brandSelect[i].id,text:brandSelect[i].text.trim()}
			  brandList.push(brands);
		  }
		  // 将数据转为 json 字符串
		  var brandJson = JSON.stringify(brandList);


		  //                specs
		  var specSelect = $("#spec2").select2("data");
		  var specList = [];
		  for (var i = 0; i <specSelect.length ; i++) {
			  var specs = {id:specSelect[i].id,text:specSelect[i].text.trim()}
			  specList.push(specs);
		  }
		  var specJson = JSON.stringify(specList);

		  //            types
		  // 先把前端的对象转换成 字符串   然后后端再进行处理
		  var typeList = [];
		  var type1 = {text:$("#td1").val()}
		  var type2 = {text:$("#td2").val()}

		  typeList.push(type1);
		  typeList.push(type2);
		  var typeListJson = JSON.stringify(typeList);

		  $.ajax({
			  url : "/type/updateTypeInfo",
			  type : "post",
			  dataType : "json",
			  async : true,
			  data : {id:$("#typeId").val(),name:$("#name").val(),specIds:specJson,brandIds:brandJson,customAttributeItems:typeListJson},
			  success : function (result) {
				  if (result.code == 10000){
					  window.location.reload();
					  alert(result.message);
				  }else if (result.code == 10001){
					  alert(result.message)
				  }
			  },
			  error : function (result) {
				  alert("网络错误,修改失败");
			  }
		  })
	  }
	  //  删除
	  function deleteByIds(id) {
		  $.ajax({
			  url : "/type/deleteTypeInfo?id="+id,
			  type : "post",
			  dataType : "json",
			  async : true,
			  success : function (result) {
				  if (result.code == 10000){
					  window.location.reload();
					  alert(result.message);
				  }else if (result.code == 10001){
					  alert(result.message)
				  }
			  },
			  error : function (result) {
				  alert("网络错误,删除失败");
			  }
		  })
	  }
	</script>

</body>
</html>